package main;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;


public class FileProcessor {

	/**
	 * @param inputName
	 * @param outputName
	 * @param checker the line processor that translate the read line, to the new line
	 */
	public static void processFile(String inputName, Integer maxSize){
		try {
			FileReader reader = new FileReader(new File(inputName));
			File f = new File(inputName.replaceAll(".js$", "") + "-tojq-temporal.js");
			FileWriter writer = new FileWriter(f);
			BufferedReader buffer = new BufferedReader(reader);
			String line;
			while ((line = buffer.readLine()) != null){
				writer.write(LineProcessor.getInstance().processLine(line) + "\n");
			}
			reader.close();
			writer.close();
			checkAjaxFromFile(inputName, maxSize);
			f.delete();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private static void checkAjaxFromFile(String inputName, Integer maxSize){
		try {
			StringBuffer fileData = new StringBuffer(maxSize);
			BufferedReader reader = new BufferedReader(new FileReader(inputName.replaceAll(".js$", "") + "-tojq-temporal.js"));
			char[] buf = new char[maxSize];
			int numRead=0;
			while((numRead=reader.read(buf)) != -1){
				String readData = String.valueOf(buf, 0, numRead);
				fileData.append(readData);
				buf = new char[maxSize];
			}			
			reader.close();
			String translation = AjaxTranslator.convertAjaxToJquery(fileData.toString());
			FileWriter writer = new FileWriter(new File(inputName.replaceAll(".js$", "") + "-tojq.js"));
			writer.write(translation);
			writer.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
}
